package cn.darkhorse.ticket.store.service.verification.impl;


import cn.darkhorse.exception.ServiceException;
import cn.darkhorse.ticket.store.dto.TicketProductDetailsDTO;
import cn.darkhorse.ticket.store.pojo.TicketInventorySurplus;
import cn.darkhorse.ticket.store.service.TicketInventoryService;
import cn.darkhorse.ticket.store.service.verification.ICalculationService.IQuantityRecordService;
import cn.darkhorse.ticket.store.service.verification.ICalculationService.MaterialUsage;
import cn.darkhorse.ticket.store.service.verification.SurplusCheckDTO;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @description:
 * @author: mr.wang
 * @time: 2024/1/18 11:14
 */
@Service("decreaseService")
public class BaseDecreaseServiceImpl extends MaterialUsage implements IQuantityRecordService {
	
	@Resource
	private TicketInventoryService inventoryService;
	
	@Override
	public void changeQuantity(List<TicketProductDetailsDTO> productList) {
		Map<String, TicketProductDetailsDTO> productMap = surplusCheckDTOMap(productList);
		Map<String, TicketInventorySurplus> surplusMap = getSurplusMap();
		rwl.writeLock().lock();
		try {
			List<TicketInventorySurplus> surplusList = new ArrayList<>();
			Set<Map.Entry<String, TicketProductDetailsDTO>> entries = productMap.entrySet();
			for(Map.Entry<String, TicketProductDetailsDTO> entry:entries){
				String key = entry.getKey();
				TicketProductDetailsDTO dto = entry.getValue();
				TicketInventorySurplus surplus = surplusMap.get(key);
				if(null == surplus){
					throw new com.ruoyi.common.exception.ServiceException(String.format("仓库-产品【%s】无记录",
						dto.getWarehouseInfoName()+"-"+dto.getProductName()));
				}
				
				surplus.setUsege(surplus.getUsege().add(dto.getQuantity()));
				surplus.setSurplus(surplus.getSurplus().subtract(dto.getQuantity()));
				surplus.setOutboundId(dto.getBusinessId());
				surplus.setWarehousingId(null);
				surplus.setId(null);
				surplus.setGmtCreate(LocalDateTime.now());
				surplus.setBusinessType(dto.getBusinessType());
				surplusList.add(surplus);
			}
			surplusService.saveBatch(surplusList);
			productList.forEach(item->{
				item.setQuantity(item.getQuantity().negate());
			});
			inventoryService.add(productList);
		} catch (DataAccessException e) {
			e.printStackTrace();
		}finally {
			rwl.writeLock().unlock();
		}
	}
	
	
	
	
	
	
}
